<?php
/**
 * User: b179a9
 * Date: 10/4/11
 * Time: 6:20 PM
 */

class ItemsController extends Zend_Controller_Action
{
    const ITEMS_PER_PAGE = 10;

    /**
     * FlashMessenger
     *
     * @var Lib_Flash
     */
    protected $_flashMessenger = null;

    public function init()
    {
        if ($this->_request->isXmlHttpRequest()) {
            $this->_helper->layout()->disableLayout();
            $response = $this->getResponse();
            $response->setHeader('Content-Type', 'text/x-json');
        } else {
            $this->_helper->layout()->setLayout('index-layout');
        }
        $this->_flashMessenger = new Lib_Flash();
    }

    public function indexAction()
    {
        $rubricsManager = new \Managers\ItemsRubrics();
        $rubrics = $rubricsManager->getList(null, true);

        $this->view->rubrics = $rubrics;
    }

    public function addAction()
    {
        $form = new App_Form_Items_Form();

        if ($this->_request->isPost()) {
            $params = $this->_request->getParams();
            if ($form->isValid($params)) {
                try {
                    $itemsManager = new \Managers\Items();
                    $item = $itemsManager->save($params);
                    $this->_flashMessenger->addMessage('Item successfully added.', Lib_Flash::NOTICE, Lib_Flash::LATER);
                    $this->_redirect('/items');
                } catch (Exception $e) {
                    die($e->getMessage());
                }
            }
        }

        $this->view->form = $form;
    }

    public function viewAction()
    {
        $rubric = $this->_request->getParam('rubric');
        $page = intval($this->_request->getParam('page', 1));

        $itemsManager = new \Managers\Items();
        $offset = $page > 0 ? ($page - 1) * self::ITEMS_PER_PAGE : 0;
        $items = $itemsManager->getByRubric($rubric, self::ITEMS_PER_PAGE, $offset);
        $total = $itemsManager->getCountByRubric($rubric);

        $paginator = new Zend_Paginator(new Zend_Paginator_Adapter_Null($total));
        $paginator->setCurrentPageNumber($page);
        $paginator->setItemCountPerPage(self::ITEMS_PER_PAGE);

        $this->view->items = $items;
        $this->view->paginator = $paginator;
        $this->view->rubric = $rubric;
        $this->view->total = $total;
    }


}
